
// Copyright (c) WanSheng Intelligent Corp. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#define LOG_TAG "ep"

#include "ep.h"
#include "wa_redis_api.h"

static redisContext * c = NULL;


static void report_ep104_data(redis_property_value_t* values, int size)
{
    for(int i=0; i< size; i++)
    {
        if(values[i].value.value_type == Redis_Value_String)
            WALOG("[%s]: string, %s", values[i].property, SAFE_STRING(values[i].value.sv));
        else if(values[i].value.value_type == Redis_Value_Float)
            WALOG("[%s]: number, %f", values[i].property, values[i].value.fv);
        else if(values[i].value.value_type == Redis_Value_Bool)
            WALOG("[%s]: number, %d", values[i].property, values[i].value.bv);
        else
            WALOG("[%s]: invalid type, %d", values[i].property, values[i].value.value_type);
    }

    //
    // Todo: post the data to server in ep104 format
    //
}

int read_from_redis(char * di, char * res, char * pt)
{
    int size;
    time_t tm;
    int fmt;
    float value;

    if(c == NULL)
        c = wa_redis_connect(1000);
    if(c == NULL)
    {
        WARNING("wa_redis_connect failed.");
        return -1;
    }
    
    redis_property_value_t* values = wa_redis_read_resource(c, di, res, &size);
    if(values)
    {
        WALOG("read electric power data: di=%s, res=%s", di, res);
        report_ep104_data(values, size);
        wa_redis_free_values(values, size);
    }
    else
    {
        redisFree(c);
        c = NULL;
    }
    return 0;
}


void cb_redis_notify(REDIS_EVENT_T event, char * subject, void * content, void * user_data)
{
    // WALOG("cb_redis_notify: sub: %s, content: %s\n", subject, content);

    if(event == Data_Value)
    {
        char * res = NULL;
        char * pt = NULL;
        char * di = wa_redis_subject_decompose(subject, &res, &pt);

        if(di == NULL || pt == NULL) return;
        read_from_redis(di, res, pt);
    }
    else if(event == AMS_Config_Update)
    {
        char * target_type = NULL;
        char * target_id = NULL;
        char * software_name = wa_redis_subject_AMS_CFG(subject, &target_type, &target_id);

        // the software name is what we defined product name in the package file "package.info"
        if(strcmp(software_name, "electric-power") == 0)
        {
            // cloud downloaded a new config file, reload it.
            load_configs();
        }
    }
}

